<script setup>
import { PlusOutlined, SearchOutlined, ClearOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import axios from "axios";
import { message } from "ant-design-vue";

//搜索条件
const formRef = ref();
const searchForm = reactive( {
  title : '', //标签名
  state : '', //状态
  create_time : [], //时间搜索
  orderField : '', //排序字段
  order : '',//排序顺序 asc|desc
} );
const onFinish = values => getTagsList( values );
const resetForm = () => formRef.value.resetFields();
const formBind = ref( {
  labelCol : { span : 4, },
  wrapperCol : { span : 12, }
} );
const onChangeDatePicker = ( date, dateString ) => {
  searchForm.create_time = dateString;
};
// TODO: 添加模态框
const formModalRef = ref();
const formData = reactive( { title : '', sort : 1, state : true, } );
const open = ref( false );
const showModal = () => open.value = true;
const handleOk = () => {
  axios.post( '/api/tags-create', formData ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
    } else {
      message.success( res.data.msg, 2, () => {
        formModalRef.value.resetFields();
        data.value.unshift( res.data.data );
        open.value = false;
        pagination.total++;
      } );
    }
  } ).catch( err => {
    console.log( err );
    message.error( '请求失败' );
  } );
};

// todo：编辑模态框
const formEditModalRef = ref();
const editFormData = reactive( { id : '', title : '', sort : 1, state : true } );
const editOpen = ref( false );
const editModal = ( id ) => {
  editOpen.value = true;
  axios.get(  '/api/tags-info?id=' + id ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
    } else {
      editFormData.id = res.data.data.id;
      editFormData.title = res.data.data.title;
      editFormData.sort = res.data.data.sort;
      editFormData.state = !!res.data.data.state;
      editOpen.value = true;
    }
  } ).catch( err => {
    console.log( err );
    message.error( '请求失败' );
  } );
};
const handleEditOk = () => {
  axios.post( '/api/tags-edit', editFormData ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
    } else {
      message.success( res.data.msg, 2, () => {
        editOpen.value = false;
        for ( let i = 0 ; i < data.value.length ; i++ ) {
          if ( data.value[i].id === editFormData.id ) {
            data.value[i].sort = editFormData.sort;
            data.value[i].state = !!editFormData.state;
            data.value[i].title = editFormData.title;
          }
        }
      } );
    }
  } ).catch( err => {
    console.log( err );
    message.error( '请求失败' );
  } );
};
const handleEditCancel = () => editOpen.value = false;

//全选
const batchDisable = computed( () => !selectData.selectedRowKeys.length > 0 );
const selectData = reactive( {
  selectedRowKeys : [],
  selectedRows : [],
  loading : false,
} );
const onSelectChange = ( selectedRowKeys, selectedRows ) => {
  selectData.selectedRowKeys = selectedRowKeys;
  selectData.selectedRows = selectedRows;
};

//表格的表头
const columns = [
  { title : 'id', dataIndex : 'id', key : 'id', sorter : true, },
  { title : '标签名', dataIndex : 'title', key : 'title', },
  { title : '状态', dataIndex : 'state', key : 'state', },
  { title : '排序', dataIndex : 'sort', key : 'sort', sorter : true, },
  { title : '添加时间', dataIndex : 'create_time', key : 'create_time', sorter : true, },
  { title : '操作', key : 'action', },
];
//分页器
const pagination = reactive( {
  current : 1,
  pageSize : 10,
  total : 0,
  showSizeChanger : true,
  showTotal : function ( total ) {
    return `共${ total }条`;
  },
  onShowSizeChange : ( current, pageSize ) => {
    pagination.current = current;
    pagination.pageSize = pageSize;
    getTagsList( searchForm );
  },
  onChange : ( page ) => {
    pagination.current = page;
    getTagsList( searchForm );
  },
} );
// 获取列表
const data = ref();
const getTagsList = ( values, filter, sorter ) => {
  if ( sorter !== undefined ) {
    if ( sorter.order === 'ascend' ) {
      searchForm.orderField = sorter.field;
      searchForm.order = 'asc';
    } else if ( sorter.order === 'descend' ) {
      searchForm.orderField = sorter.field;
      searchForm.order = 'desc';
    } else {
      searchForm.orderField = '';
      searchForm.order = '';
    }
  }
  let params = {
    page : pagination.current,
    pageSize : pagination.pageSize,
    title : searchForm.title,
    orderField : searchForm.orderField,
    order : searchForm.order,
    ...values,
  };
  axios.get( '/api/tags-list', { params : params } ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
    } else {
      data.value = res.data.data.list.map( item => {
        item.key = item.id;//批量选择时需设置key
        item.state = !!item.state;
        return item;
      } );
      pagination.total = res.data.data.total;
      pagination.current = parseInt( res.data.data.page );
      pagination.pageSize = parseInt( res.data.data.pageSize );
    }
  } ).catch( err => {
    console.log( err );
    message.error( '请求失败' );
  } );
}

// 修改标签状态
const handleChangeState = ( id, $event ) => {
  let value = $event ? 1 : 0;
  axios.post(  '/api/tags-edit', { id : id, state : value } ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
    } else {
      message.success( res.data.msg );
    }
  } ).catch( err => {
    console.log( err );
    message.error( '请求失败' );
  } );
}

// 删除标签
const handleDelete = ( id ) => {
  axios.post( '/api/tags-delete', { id : id } ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
      return false;
    } else {
      message.success( res.data.msg, 1, () => {
        data.value = data.value.filter( item => item.id !== id );
        pagination.total--;
      } );
    }
  } ).catch( err => {
    console.log( err );
    message.error( '请求失败' );
  } );
}

// 批量删除
const handleBatchDelete = () => {
  selectData.loading = true;
  if ( selectData.selectedRowKeys.length === 0 ) {
    message.error( '请选择要删除的数据' );
    return false;
  }
  axios.post(  '/api/tags-batch-delete', {
    ids : selectData.selectedRowKeys.join( ',' )
  } ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
    } else {
      selectData.loading = false;
      message.success( res.data.msg, 1, () => {
        data.value = data.value.filter( item => !selectData.selectedRowKeys.includes( item.id ) );
      } )
    }
  } )
}


// 页面加载时调用
onMounted( () => {
  getTagsList( searchForm );
} );
</script>

<template>
  <!-- 添加标签模态框 -->
  <template>
    <a-modal v-model:open="open" title="添加标签" ok-text="确定" cancel-text="取消" @ok="handleOk" @cancel="() => open = false">
      <a-form name="addModal" ref="formModalRef" :model="formData" v-bind="formBind">
        <a-form-item label="标签名称" name="title" :rules="[{ required: true, message: '请输入标签名称' }]" required>
          <a-input v-model:value="formData.title" placeholder="请填写标签名称" autocomplete="off"></a-input>
        </a-form-item>
        <a-form-item label="标签状态" name="state">
          <a-switch v-model:checked="formData.state" checked-children="启用" un-checked-children="禁用" v-remove-aria-hidden/>
        </a-form-item>
        <a-form-item label="排序" name="sort" style="margin: 5px" required>
          <a-input-number v-model:value="formData.sort" :min="1" :max="999" style="width: 100%"></a-input-number>
        </a-form-item>
      </a-form>
    </a-modal>
  </template>
  
  <!-- 编辑标签 -->
  <template>
    <a-modal v-model:open="editOpen" title="编辑标签" ok-text="确定" cancel-text="取消" @ok="handleEditOk" @cancel="handleEditCancel">
      <a-form name="editModal" ref="formEditModalRef" v-bind="formBind" :model="editFormData">
        <a-form-item label="标签名称" name="title" :rules="[{ required: true, message: '请输入标签名称' }]" required>
          <a-input v-model:value="editFormData.title" placeholder="请填写标签名称" autocomplete="off"></a-input>
        </a-form-item>
        <a-form-item label="标签状态" name="state">
          <a-switch v-model:checked="editFormData.state" checked-children="启用" un-checked-children="禁用" v-remove-aria-hidden/>
        </a-form-item>
        <a-form-item label="排序" name="sort" style="margin: 5px" required>
          <a-input-number v-model:value="editFormData.sort" :min="1" :max="999" style="width: 100%"></a-input-number>
        </a-form-item>
      </a-form>
    </a-modal>
  </template>
  
  <a-space size="middle">
    <a-form layout="inline" ref="formRef" name="tags_search" :model="searchForm" @finish="onFinish">
      <a-form-item label="标签名称" name="title">
        <a-input v-model:value="searchForm.title" allow-clear></a-input>
      </a-form-item>
      <a-form-item label="状态" name="state">
        <a-select v-model:value="searchForm.state" placeholder="请选择状态">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="1">启用</a-select-option>
          <a-select-option value="0">禁用</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="添加时间" name="create_time">
        <a-range-picker style="width: 260px" format="YYYY-MM-DD" :allow-clear="true" :placeholder="['开始时间', '结束时间']" @change="onChangeDatePicker"/>
      </a-form-item>
      <a-row>
        <a-button type="primary" html-type="submit">
          <search-outlined/>
          搜索
        </a-button>
        <a-button style="margin: 0 8px" @click="resetForm">
          <clear-outlined/>
          Clear
        </a-button>
      </a-row>
    </a-form>
  </a-space>
  
  <div style="margin: 10px 0">
    <a-space style="margin-bottom: 10px">
      <a-button type="primary" @click="showModal">
        <PlusOutlined/>
        添加数据
      </a-button>
      <a-button type="primary" @click="handleBatchDelete" :disabled="batchDisable" :loading="selectData.loading">
        <DeleteOutlined/>
        批量删除
      </a-button>
    </a-space>
    
    <a-table
        bordered
        @change="getTagsList"
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        :show-sorter-tooltip="true"
        :row-selection="{ selectedRowKeys: selectData.selectedRowKeys, onChange: onSelectChange }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'title'">
          <a>{{ record.title }}</a>
        </template>
        <template v-else-if="column.key === 'state'">
          <a-switch v-model:checked="record.state" checked-children="启用" un-checked-children="禁用"
              @change="handleChangeState(record.id, $event)"/>
        </template>
        
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="editModal(record.id)">编辑</a-button>
            <a-popconfirm title="确认删除吗?" @confirm="handleDelete(record.id)" ok-text="确认" cancel-text="删除">
              <a-button type="primary" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<style scoped>

</style>